package com.jfree.servlet;

import java.awt.Font;
import java.io.PrintWriter;

import javax.servlet.http.HttpSession;

import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.labels.StandardPieToolTipGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.ui.RectangleInsets;

public class CakeServlet {

	public static String generatePieChart(String infoStr, String titles,
			HttpSession session, PrintWriter pw) {
		String filename = null;
		Font font;

		try {
			// 建立PieDataSet
			DefaultPieDataset data = new DefaultPieDataset();
			String ss[] = infoStr.split(",");
			for (int n = 0; n < ss.length; n++) {
				String ssPart[] = ss[n].split("#");
				int tt = Integer.parseInt(ssPart[1]);
				String mm = ssPart[0];
				data.setValue(mm, tt);
			}

			// 生成chart物件
			PiePlot plot = new PiePlot(data);
			plot.setInsets(new RectangleInsets(0, 5, 5, 5));

			plot.setToolTipGenerator(new StandardPieToolTipGenerator());
			// 这个地方是设置统计图标题的字体和大小
			font = new Font("黑体", Font.CENTER_BASELINE, 20);

			JFreeChart chart = new JFreeChart("",
					JFreeChart.DEFAULT_TITLE_FONT, plot, true);

			TextTitle tt = new TextTitle(titles);
			tt.setFont(font);
			// 设置统计图片的底色
			chart.setBackgroundPaint(java.awt.Color.white);
			chart.setTitle(tt);

			// 把生成的文件写入到临时的目录中
			ChartRenderingInfo info = new ChartRenderingInfo(
					new StandardEntityCollection());
			// 选择存储成jpeg格式的文件，当然你也可以使用saveChartAsPNG的方法生成png图片
			filename = ServletUtilities.saveChartAsJPEG(chart, 500, 300, info,
					session);

			// 把image map 写入到 PrintWriter
			ChartUtilities.writeImageMap(pw, filename, info, false);
			pw.flush();
		} catch (Exception ex) {
			System.out.println("error:" + ex.getMessage());
		}
		return filename;
	}
}